<template>
  <el-dialog
      ref="dialog"
      width="85%"
      v-model="visible"
      :title="title"
  >
    <el-container>
      <el-row :gutter="20">
        <el-col :xs="24" :sm="24" :lg="12">
          <el-card>
            <el-form ref="formRef" :model="form" :rules="rules" label-width="90px">
              <el-form-item label="协作标题：" prop="taskName">
                <span v-if="!editable.taskName" @click="makeEditable('taskName')">{{ form.taskName }}</span>
                <el-input v-else v-model="form.taskName" :ref="el => refs.taskName = el"
                          @blur="makeUneditable('taskName')"
                />
              </el-form-item>

              <el-form-item label="完成状态：" prop="finishState">
                <dict-tag
                    v-show="!editable.finishState" @click="makeEditable('finishState')"
                    :type="DICT_TYPE.BUSINESS_FINISH_STATUS" :value="form.finishState"
                />
                <el-select
                    v-show="editable.finishState" v-model="form.finishState" :ref="el => refs.finishState = el"
                    placeholder="请选择完成状态"
                    @change="makeUneditable('finishState')" @blur="editable.finishState = false"
                >
                  <el-option
                      v-for="dict in getDictOptions(DICT_TYPE.BUSINESS_FINISH_STATUS)"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                  />

                </el-select>
              </el-form-item>

              <el-form-item label="执行状态：" prop="executeState">
                <dict-tag
                    v-show="!editable.executeState" @click="makeEditable('executeState')"
                    :type="DICT_TYPE.BUSINESS_FINISH_STATUS" :value="form.executeState"
                />
                <el-select
                    v-show="editable.executeState" v-model="form.executeState" :ref="el => refs.executeState = el"
                    placeholder="请选择执行状态"
                    @change="makeUneditable('executeState')" @blur="editable.executeState = false"
                >
                  <el-option
                      v-for="dict in getDictOptions(DICT_TYPE.BUSINESS_FINISH_STATUS)"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                  />
                </el-select>
              </el-form-item>


              <el-form-item label="执行人：" prop="executeUser">
                <cascader-user
                    v-model="form.executeUser" @blur="makeUneditable('executeUser')" :ref="el => refs.executeUser = el"
                    placeholder="执行人" @change="makeUneditable('executeUser')"
                />
              </el-form-item>

              <el-form-item label="截止时间：" prop="deadline">
                <el-date-picker
                    v-model="form.deadline"
                    type="datetime"
                    value-format="x"
                    placeholder="请选择协作项截止时间"

                    @change="makeUneditable('deadline')"
                />
              </el-form-item>

              <el-form-item label="优先级：" prop="priority">
                <span v-show="!editable.priority" @click="makeEditable('priority')">{{ form.priority }}</span>
                <!--                <dict-tag-->
                <!--                    v-show="!editable.priority" @click="makeEditable('priority')"-->
                <!--                    :options="DICT_TYPE.BUSINESS_PRIORITY" :value="form.priority"-->
                <!--                />-->
                <el-select
                    v-show="editable.priority" v-model="form.priority" :ref="el => refs.priority = el"
                    placeholder="请选择完成状态"
                    @change="makeUneditable('priority')" @blur="editable.priority = false"
                >
                  <el-option
                      v-for="dict in getDictOptions(DICT_TYPE.BUSINESS_PRIORITY)"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                  />
                </el-select>
              </el-form-item>

              <el-form-item label="协作内容：" prop="content">
                <span v-if="!editable.content" @click="makeEditable('content', $event)" v-html="form.content"></span>
                <div v-else>
                  <editor v-model="form.content" :min-height="192"/>
                  <div style="float: right;margin: 5px 0px">
                    <el-button type="text" @click="editable.content = false">取消</el-button>
                    <el-button type="primary" @click="makeUneditable('content')">保存</el-button>
                  </div>
                </div>
              </el-form-item>

              <el-form-item label="关联文件：" prop="taskFile">
                <upload-file v-model="form.taskFile" :is-show-tip="false"/>
                <el-button size="small" type="primary" @click="submitFile">保存</el-button>
              </el-form-item>

              <el-form-item label="协助人：" prop="assistUser">
                <cascader-user v-model="form.assistUser" placeholder="协助人" @change="makeUneditable('assistUser')"/>
              </el-form-item>
            </el-form>
          </el-card>
        </el-col>

        <el-col :xs="24" :sm="24" :lg="12">
          <el-card class="box-card">
            <template #header>
              <div class="clearfix">
                <span>所有动态</span>
                <el-button
                    style="float: right; padding: 3px 0" type="text" icon="el-icon-refresh"
                    @click="getTaskDetails(form)"
                >刷新
                </el-button>
              </div>
            </template>
            <div class="remark-content">
              <div v-for="log in logList" :key="log.id">
                <div class="remark-item">
                  <!-- 操作 -->
                  <div v-if="log.type === '操作'" class="remark-handle">
                    <span style="float: right">{{ formatDate(log.createTime) }}</span>
                    <span
                        class="remark-item-content-text" v-html="log.content" style="width: 100%"
                        @click="openImg($event)"
                    ></span>
                  </div>

                  <!-- 备注 -->
                  <div v-else class="remark-remark">
                    <div class="topRemark">
                      <div>
                        <img
                            class="user-avatar"
                            :src="log.avatar ? log.avatar : 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'"
                        />
                        <span style="font-size: 15px;line-height: 30px; padding-left: 5px;"
                        >{{ log.creator_dictText }}</span>
                      </div>
                      <div style="float: right;">
                        <span style="font-size: 15px;line-height: 30px">{{ formatDate(log.createTime) }}</span>
                      </div>
                    </div>

                    <div class="bottomRemark"></div>

                    <div class="remark-item-content">
                      <span
                          class="remark-item-content-text" v-html="log.content" style="width: 100%"
                          @click="openImg($event)"
                      ></span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <el-divider/>
            <el-row :gutter="5">
              <el-col :span="22">
                <div class="remark-bottom">
                  <editor v-model="content" max-height="120"/>
                </div>
              </el-col>
              <el-col :span="2">
                <el-button type="primary" @click="handleAddRemark">评论</el-button>
              </el-col>
            </el-row>
          </el-card>
        </el-col>
      </el-row>
    </el-container>

    <el-dialog
        append-to-body
        title="评价"
        v-model="rateVisible"
        width="30%"
    >
      <el-form ref="rateFormRef" :model="form" label-width="100px">
        <el-form-item label="满意程度：" prop="templateImg">
          <el-rate v-model.number="form.score"/>
        </el-form-item>
        <el-form-item label="评论：" prop="templateImg">
          <el-input
              type="textarea"
              :rows="2"
              placeholder="请输入内容"
              v-model="form.scoreDesc"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="rateVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitFinish">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </el-dialog>
</template>

<script setup>

import {useUserStore} from "@/store/modules/user";
import {ProjectTaskApi} from '@/api/business/synergy/project/task'
import {ProjectTaskLogApi} from '@/api/business/synergy/project/taskLog'
import {DICT_TYPE, getDictOptions} from '@/utils/dict'
import {formatDate} from "../../../../../utils/formatTime";

const message = useMessage() // 消息弹窗
const userStore = useUserStore()


// 响应式变量
const visible = ref(false)
const rateVisible = ref(false)
const title = ref('')
const content = ref('')
let form = ref({})
const logList = ref([])
const formRef = ref(null)
const rateFormRef = ref(null)
const tempData = ref('')

const refs = reactive({})


// 编辑状态管理
const editable = reactive({
  taskName: false,
  finishState: false,
  executeState: false,
  executeUser: false,
  deadline: false,
  priority: false,
  label: false,
  content: false,
  taskFile: false,
  assistUser: false
})

// 验证规则
const rules = ref({})

const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调

// 打开图片预览
const openImg = (e) => {
  if (e.target.nodeName === 'IMG') {
    if (e.target.src.startsWith('data:image')) {
      // 如果是 base64 格式的图片，创建临时链接并在新标签页中显示
      let byteCharacters = atob(e.target.src.split(',')[1])
      let byteNumbers = new Array(byteCharacters.length)
      for (let i = 0; i < byteCharacters.length; i++) {
        byteNumbers[i] = byteCharacters.charCodeAt(i)
      }
      let byteArray = new Uint8Array(byteNumbers)
      let blob = new Blob([byteArray], {type: 'image/png'})
      let imageUrl = URL.createObjectURL(blob)
      window.open(imageUrl, '_blank')
    } else {
      // 如果不是 base64 格式的图片，直接在新标签页中显示
      window.open(e.target.src, '_blank')
    }
  }
}

// 打开任务详情
const showVisible = (task) => {
  console.log(task, 'task')
  title.value = `模板：${task.templateId_dictText}--${task.typeId_dictText}`
  visible.value = true
  getTaskDetails(task)
}

// 获取任务详情
const getTaskDetails = async (task) => {
  form.value = await ProjectTaskApi.getProjectTask(task.id)
  let data = await ProjectTaskLogApi.getProjectTaskLogPage({taskId: task.id})
  logList.value = data.list
  await nextTick(() => {
    const chatContainer = document.querySelector('.remark-content')
    if (chatContainer && chatContainer.scrollHeight) {
      chatContainer.scrollTop = chatContainer.scrollHeight
    }
  })
}

// 切换到编辑状态
const makeEditable = (field, $event) => {
  if (field === 'finishState') {
    if (userStore.user.id !== '1') {
      if (form.value.creator !== userStore.user.id.toString()) {
        message.error('您不是创建者，不能修改状态')
        return
      }
    }
  }

  tempData.value = form.value[field]
  if (field === 'content' && $event) {
    openImg($event)
  }

  editable[field] = true

  nextTick(() => {
    // 直接通过 refs[field] 访问组件，调用 focus 方法
    refs[field]?.focus()  // ?. 防止字段不存在时报错
  })
}

// 切换到非编辑状态
const makeUneditable = (field) => {
  editable[field] = false

  if (!form.value[field]) return
  debugger
  // 在失去焦点时进行必要的数据处理或校验
  if (field === 'finishState' && form.value.finishState === '已完成') {
    rateVisible.value = true
  } else {
    if (tempData.value === form.value[field]) return
    updateTaskHandler(field)
  }
}

// 提交文件
const submitFile = () => {
  if (form.value.taskFile) {
    updateTaskHandler('taskFile')
  }
}

// 提交评价
const submitFinish = () => {
  rateVisible.value = false
  updateTaskHandler('finishState,scoreDesc,score')
}

// 更新任务
const updateTaskHandler = async (column) => {
  form.value.params = {column: column}
  await ProjectTaskApi.updateProjectTask(form.value)
  emit('success');
  message.success("操作成功")
  await getTaskDetails(form.value)
}

// 添加评论
const handleAddRemark = async () => {
  const logForm = {
    taskId: form.value.id,
    content: content.value,
    type: '备注'
  }
  await ProjectTaskLogApi.createProjectTaskLog(logForm)
  content.value = ''
  await getTaskDetails(form.value)
}

// 暴露方法给父组件
defineExpose({
  showVisible
})


</script>


<style scoped>
/* 动态列表容器优化 */
:deep(.remark-content) {
  overflow: auto;
  height: 500px !important;
  padding: 15px;
  background-color: #f9fafb;
  border-radius: 8px;
  box-sizing: border-box;

  /* 滚动条美化 */

  &::-webkit-scrollbar {
    width: 6px;
  }

  &::-webkit-scrollbar-thumb {
    background-color: #d1d5db;
    border-radius: 3px;
  }

  &::-webkit-scrollbar-thumb:hover {
    background-color: #9ca3af;
  }
}

/* 单个动态项容器 - 统一基础样式 */
:deep(.remark-item) {
  margin-bottom: 2px; /* 减小项之间的间距 */
  padding: 2px 0; /* 增加内部上下边距 */
  transition: all 0.2s ease;

  &:last-child {
    margin-bottom: 0;
  }

  &:hover {
    transform: translateY(-1px);
  }
}

/* 操作类型动态样式（系统日志）- 去除容器感 */
:deep(.remark-handle) {
  color: #6b7280;
  padding: 5px 0; /* 仅保留上下内边距 */
  font-size: 13px;
  line-height: 1.5;

  /* 系统提示时间样式 */

  span[style*="float: right"] {
    color: #9ca3af;
    margin-left: 8px;
    font-size: 12px;
  }

  .remark-item-content-text {
    display: block;
    padding: 2px 0;
  }
}

/* 用户备注动态样式 - 减小间距 */
:deep(.remark-remark) {
  position: relative;
  padding: 4px 10px; /* 减小内边距 */
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 3px 6px rgba(0, 0, 0, 0.05);

  &::before {
    content: '';
    position: absolute;
    left: 5px;
    top: 16px;
    width: 4px;
    height: 4px;
    border-radius: 50%;
    background: #409eff;
  }

  /* 头像和时间所在的顶部容器 */

  .topRemark {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-bottom: 5px; /* 减小底部间距 */
    margin-bottom: 5px; /* 减小与内容的间距 */
    border-bottom: 1px dashed #f0f0f0;
    height: 25px; /* 略微减小高度 */
  }

  /* 头像和用户名容器 */

  .topRemark div:first-child {
    display: flex;
    align-items: center;
    height: 100%;
  }

  /* 头像样式 */

  .user-avatar {
    width: 30px !important; /* 适当减小头像 */
    height: 30px !important;
    border-radius: 50%;
    margin-right: 8px;
    margin-top: 8px;
    border: 1px solid #eee;
    flex-shrink: 0;
    transition: transform 0.2s ease;

    &:hover {
      transform: scale(1.05);
    }
  }

  /* 用户名 */

  .topRemark span:first-of-type {
    font-weight: 500;
    color: #333;
    line-height: 28px; /* 与头像高度匹配 */
  }

  /* 时间容器 */

  .topRemark div:last-child {
    display: flex;
    align-items: center;
    height: 100%;
  }

  /* 时间文本 */

  .topRemark span:last-of-type {
    font-size: 12px;
    color: #999;
    line-height: 28px; /* 与头像高度匹配 */
    white-space: nowrap;
  }

  /* 评论内容区域 */

  .remark-item-content {
    padding-left: 14px; /* 与左侧标识对齐 */

    .remark-item-content-text {
      line-height: 1.5; /* 减小行高 */
      color: #444;
      word-break: break-all;
      font-size: 14px;
    }
  }
}

/* 动态内容中的图片优化 */
:deep(.remark-item-content-text img) {
  max-width: 30%;
  height: auto;
  border-radius: 4px;
  margin: 6px 0; /* 减小图片上下间距 */
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  cursor: zoom-in;
  transition: all 0.3s ease;

  &:hover {
    transform: translateY(-2px);
  }
}

/* 底部评论区与动态列表分隔 */
:deep(.el-divider) {
  margin: 12px 0; /* 减小分隔线上下间距 */
  background-color: #e5e7eb;
}

/* 评论输入区样式优化 */
.remark-bottom {
  max-height: 150px; /* 减小最大高度 */
  overflow-y: auto;
  padding: 6px; /* 减小内边距 */
  border: 1px solid #e5e7eb;
  border-radius: 6px;
  transition: border-color 0.2s ease;

  &:focus-within {
    border-color: #3b82f6;
    box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.1);
  }
}

/* 评论按钮优化 */
:deep(.el-col:nth-child(2) .el-button) {
  margin-top: 6px; /* 减小按钮顶部间距 */
  transition: all 0.2s ease;

  &:hover {
    transform: translateY(-1px);
  }
}
</style>




